package com.dh.convert.rule.function;

import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import com.alibaba.fastjson.util.TypeUtils;
import com.dh.convert.utils.ClassUtils;
import com.googlecode.aviator.runtime.function.AbstractFunction;
import com.googlecode.aviator.runtime.function.FunctionUtils;
import com.googlecode.aviator.runtime.type.AviatorNil;
import com.googlecode.aviator.runtime.type.AviatorObject;
import com.googlecode.aviator.runtime.type.AviatorRuntimeJavaType;

public class CastFunction extends AbstractFunction{

	 @Override
     public AviatorObject call(Map<String, Object> env, AviatorObject arg ,AviatorObject arg1) {
		 String typeName =  FunctionUtils.getStringValue(arg1, env);
		 Object o =  FunctionUtils.getJavaObject(arg, env);
		 if(o  == null){
			 return AviatorNil.NIL;
		 }
		 if(StringUtils.isBlank(typeName) ||ClassUtils.getTypeClass(typeName) == null){
			 return new AviatorRuntimeJavaType(o);
		 }
		 return new AviatorRuntimeJavaType(TypeUtils.castToJavaBean(o, ClassUtils.getTypeClass(typeName)));
     }
	@Override
	public String getName() {
		return "cast";
	}

}
